package lobby;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/game")
public class Game extends HttpServlet {
	int gameCounter = 1;
	JSONObject mangud = new JSONObject();
	public String toJson(ArrayList<String> input) {
		JSONObject json = new JSONObject();
		for(int i=0;i<(input.size());i=i+2){
			json.put(input.get(i),input.get(i+1));
		}
		return json.toJSONString();
 		
	}
	public void doGet(HttpServletRequest request,
            HttpServletResponse response)
	throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		out.print(mangud.toJSONString());
		out.flush();
		
		
	}
	public void doPost(HttpServletRequest request,
            HttpServletResponse response)
	throws ServletException, IOException {
		String status = request.getParameter("Status");
		int statusInt = Integer.parseInt(status);
		if (statusInt==2)
		{
			JSONArray jsonArray = new JSONArray();
			String playerName = request.getParameter("Name");
			jsonArray.add(Integer.toString(statusInt));
			jsonArray.add(playerName);
			mangud.put(Integer.toString(gameCounter),jsonArray);
			ArrayList<String> json = new ArrayList<String>();
			json.add("gameId");
			json.add(Integer.toString(gameCounter));
			PrintWriter out = response.getWriter();
			out.print(toJson(json));
			out.flush();
			gameCounter+=1;
			
		}
		else if (statusInt==3)
		{
			String playerName = request.getParameter("Name");
			String gameID = request.getParameter("GameID");
			JSONArray gameInfo = (JSONArray) mangud.get(gameID);
			gameInfo.add(playerName);
			gameInfo.set(0,Integer.toString(3));
			mangud.put(gameID,gameInfo);
		}
		else if (statusInt==0)
		{
			String gameID = request.getParameter("GameID");
			mangud.remove(gameID);
		}

	}
}
